package com.factory.manager.controller;

import com.factory.common.pojo.Result;
import com.factory.common.utils.DateUtil;
import com.factory.common.utils.StringUtil;
import com.factory.manager.service.UserDevicesService;
import com.factory.manager.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@RestController
@RequestMapping("/manager/index")
@Slf4j
public class IndexController {

    @Value("${jiexun.upload.dir}")
    private String dir;

    @Autowired
    private UserService userService;

    @Autowired
    private UserDevicesService userDevicesService;

    /**
     * 用户上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("文件不能为空");
        }

        String type = file.getOriginalFilename();
        type = type.substring(type.lastIndexOf("."));

        //String filePath = "upload" + File.separator + DateUtil.getDateString(new Date(), "yyyy-MM-dd"), fileName = StringUtil.getUUID() + type;
        String filePath = "temp" + File.separator + DateUtil.getDateString(new Date(), "yyyy-MM-dd"), fileName = StringUtil.getUUID() + type;

        File path = new File(dir + filePath);
        if (!path.exists())
            path.mkdirs();

        String picturePath = filePath + File.separator + fileName;
        try {
            file.transferTo(new File(dir + picturePath));
        } catch (IOException e) {
            log.error(e.toString(), e);
            return Result.fail(null, "上传失败", 500);
        }

        return Result.success(picturePath, "上传成功");
    }

    /**
     * 首页数据统计
     * @return
     */
    @RequestMapping("/statistics")
    public Result statistics(){
        log.info("首页数据统计");

        Map<String,Object> statistics = new HashMap<>();
        statistics.put("userCount",userService.count());
        statistics.put("userDevicesCount",userDevicesService.statistics(new HashMap<>()));

        return Result.success(statistics,"查询成功!");
    }
}
